package com.ruoyi.weiriya.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WMember;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.weiriya.domain.*;
import com.ruoyi.weiriya.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.weiriya.mapper.WAreaMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 小区信息（停车点位）Service业务层处理
 * 
 * @author lynn
 * @date 2023-08-01
 */
@Service
public class WAreaServiceImpl extends ServiceImpl<WAreaMapper, WArea> implements IWAreaService
{
    @Autowired
    private IWUserAreaService userAreaService;

    @Autowired
    private IWCompanyService companyService;

    @Autowired
    private IWMemberService memberService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IWVehicleChargeTypeService vehicleChargeTypeService;

    @Autowired
    private IWVehicleNonChargeTypeService vehicleNonChargeTypeService;

    @Autowired
    private IWVipSettingService vipSettingService;

    @Autowired
    private IWNonVipSettingService nonVipSettingService;

    @Autowired
    private WAreaMapper areaMapper;

    @Transactional
    @Override
    public boolean saveWArea(WArea wArea) {
        if(StringUtils.isNotBlank(wArea.getCompanyId())) {
            WCompany company = companyService.getById(wArea.getCompanyId());
            if(StringUtils.isNull(company)){
                throw new ServiceException("公司不存在！");
            }
        }

        if(StringUtils.isNotBlank(wArea.getUserId())) {
            SysUser sysUser = userService.selectUserById(Long.valueOf(wArea.getUserId()));
            if (StringUtils.isNull(sysUser)) {
                throw new ServiceException("管理员不存在！");
            }
        }
        this.save(wArea);

        // 创建价格相关数据
        List<WVehicleChargeType> chargeList = vehicleChargeTypeService.list();
        List<WVipSetting> vipSettingList = new ArrayList<>();
        for (WVehicleChargeType type : chargeList) {
            WVipSetting wVipSetting = new WVipSetting();
            wVipSetting.setAreaId(wArea.getId());
            wVipSetting.setSettingType(1);
            wVipSetting.setVehicleType(type.getId());
            vipSettingList.add(wVipSetting);
        }
        List<WVehicleNonChargeType> nonChargeList = vehicleNonChargeTypeService.list();
        for (WVehicleNonChargeType type : nonChargeList) {
            WVipSetting wVipSetting = new WVipSetting();
            wVipSetting.setAreaId(wArea.getId());
            wVipSetting.setSettingType(2);
            wVipSetting.setVehicleType(type.getId());
            vipSettingList.add(wVipSetting);
        }
        vipSettingService.saveBatch(vipSettingList);

        WNonVipSetting wNonVipSetting = new WNonVipSetting();
        wNonVipSetting.setAreaId(wArea.getId());
        nonVipSettingService.save(wNonVipSetting);

        return true;

    }

    @Transactional
    @Override
    public boolean updateWAreaById(WArea wArea) {

        WArea area = this.getById(wArea.getId());

        if(StringUtils.isNotBlank(wArea.getCompanyId())) {
            // 不相同则验证
            if(!wArea.getCompanyId().equals(area.getCompanyId())) {
                WCompany company = companyService.getById(wArea.getCompanyId());
                if (StringUtils.isNull(company)) {
                    throw new ServiceException("公司不存在！");
                }
            }
        }

        if(StringUtils.isNotBlank(wArea.getUserId())) {
            if(!wArea.getUserId().equals(area.getUserId())) {
                SysUser sysUser = userService.selectUserById(Long.valueOf(wArea.getUserId()));
                if (StringUtils.isNull(sysUser)) {
                    throw new ServiceException("管理员不存在！");
                }

                WUserArea wUserArea = new WUserArea();
                wUserArea.setUserId(wArea.getUserId());
                wUserArea.setAreaId(wArea.getId());
                userAreaService.saveWUserArea(wUserArea);
                if(StringUtils.isNotBlank(area.getUserId())) {
                    userAreaService.remove(new LambdaQueryWrapper<WUserArea>()
                            .eq(WUserArea::getAreaId, area.getId())
                            .eq(WUserArea::getUserId, area.getUserId()));
                }
            }
        }
        return this.updateById(wArea);
    }

    @Override
    public List<WArea> getList(WArea wArea) {
        QueryWrapper<WArea> queryWrapper = wArea.queryWrapper();
        if(StringUtils.isNotBlank(SecurityUtils.getLoginUser().getUser().getCompanyId())){
            List<String> areaIdListByUserId = companyService.getAreaIdList();
            if(areaIdListByUserId.size() > 0) {
                queryWrapper.in("a.id", areaIdListByUserId);
            } else {
                return new ArrayList<>();
            }
        }
        return areaMapper.getList(queryWrapper);
    }

    @Transactional
    @Override
    public boolean removeWAreaByIds(List<String> ids) {
        // 检查点位是否已存在用户
        long count = memberService.count(new LambdaQueryWrapper<WMember>()
                .in(WMember::getAreaId, ids));
        if(count > 0) throw new ServiceException("该点位已存在用户，不可删除！");

        // 删除管理员与点位的绑定
        userAreaService.remove(new LambdaQueryWrapper<WUserArea>()
                .in(WUserArea::getAreaId, ids));
        return this.removeBatchByIds(ids);
    }

    @Override
    public WArea getWAreaById(String id) {
        return areaMapper.getWAreaById(id);
    }

}
